package com.fdd.furns.web;

import com.fdd.furns.pojo.Furn;
import com.fdd.furns.pojo.Page;
import com.fdd.furns.service.FurnService;
import com.fdd.furns.service.impl.FurnServiceImpl;
import com.fdd.furns.utils.DataUtils;
import com.fdd.furns.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@WebServlet(urlPatterns = {"/manage/furnServlet"})
public class FurnServlet extends BasicServlet {
    FurnService furnService = new FurnServiceImpl();

    //查询所有家居信息
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        System.out.println("进入了list方法");
        List<Furn> furns = furnService.queryFurns();
        req.setAttribute("furns", furns);

        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }

    //添加家居信息
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("进入了add方法");

        try {
//            String name = req.getParameter("name");
//            String maker = req.getParameter("maker");
//            double price = Double.parseDouble(req.getParameter("price"));
//            int sales = Integer.parseInt(req.getParameter("sales"));
//            int stock = Integer.parseInt(req.getParameter("stock"));
//            String imgPath = req.getParameter("imgPath");
//            furn = new Furn(0, name, maker, price, sales, stock, imgPath);
            Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
            furnService.addFurn(furn);
            resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo") + "&pageSize=" + req.getParameter("pageSize"));
        } catch (Exception e) {
            req.setAttribute("msg", "添加的数据格式不对");
            req.getRequestDispatcher("/views/manage/furn_add.jsp").forward(req, resp);
        }
    }


    protected void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        furnService.deleteFurnById(id);
        //重定向到家居列表
        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo") + "&pageSize=" + req.getParameter("pageSize"));

    }

    //根据id查询家居信息
    protected void getFurnById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        req.setAttribute("furn", furn);
        req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req, resp);
    }

    //修改家居信息
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
//        furnService.updateFurn(furn);//没有修改imgPath
//        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo") + "&pageSize=" + req.getParameter("pageSize"));
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        //获取到要修改的家居信息
        Furn furn = furnService.queryFurnById(id);
        //furn 不为空，继续往下

        if (ServletFileUpload.isMultipartContent(req)) {
            // 说明有文件上传
            // 1. 创建一个FileItemFactory工厂实现类，用于解析数据
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            // 2. 创建一个文件上传解析器,servletFileUpload可以把表单中的数据封装成一个FileItem对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

            try {
                // 3. 开始解析上传数据
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        // 普通表单项,文本
//                        String name = fileItem.getString("utf-8");
//                        System.out.println("家具名=" + name);
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("utf-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("utf-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString("utf-8")));
                        }

                    } else {
                        // 上传的文件
                        String name = fileItem.getName();
                        //
                       if(name != null && !"".equals(name)) {

                           //保存文件
                           //1.指定一个目录
                           String filePath = WebUtils.FURN_IMG_DIRECTORY;
                           //获取项目的真实路径
                           String realPath = this.getServletContext().getRealPath(filePath);

                           //2.保存文件
                           //先要去创建目录
                           File fileRealPathDirectory = new File(realPath);
                           if (!fileRealPathDirectory.exists()) {
                               fileRealPathDirectory.mkdirs();//不存在目录就创建
                           }

                           //为了保证文件重名不会被覆盖，还要去对文件名做处理
                           name = UUID.randomUUID() + "_" + name;


                           //3.保存文件
                           fileItem.write(new File(fileRealPathDirectory, name));
                           //关闭流
                           fileItem.getOutputStream().close();

                           //更新家居的图片路径
                           furn.setImgPath(filePath + "/" + name);
                       }

                    }
                    //更新家居信息
                    furnService.updateFurn(furn);
                    //转发到更新成功页面
                    req.getRequestDispatcher("/views/manage/update_ok.jsp").forward(req, resp);

                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    //根据pageNo和pageSize查询家居page页面
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo, pageSize);
        req.setAttribute("page", page);
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }
}


